package com.wawei.seeds.champion;

import android.app.Activity;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.wawei.seeds.R;
import com.wawei.seeds.adapter.ChampionCommentAdapter;
import com.wawei.seeds.model.CommentModel;
import com.wawei.seeds.services.WalnutCommentServiceHandler;
import com.wawei.seeds.utils.PrefUtils;
import com.wawei.seeds.utils.PullupToMoreListView;
import com.wawei.seeds.utils.RetrofitNetworkService;
import com.wawei.seeds.utils.WalnutBaseNofityHandler;
import com.wawei.seeds.utils.WalnutNotifyHandler;
import com.wawei.seeds.utils.WalnutUtils;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit.RestAdapter;

/**
 * Created by itachi on 15/8/1.
 */
public class ChampionCommentActivity extends Activity {
    @InjectView(R.id.walnut_logo)ImageView logoImage;
    @InjectView(R.id.walnut_comment_pull_refresh)SwipeRefreshLayout swipeRefreshLayout;
    @InjectView(R.id.walnut_comment_list)PullupToMoreListView commentList;
    @InjectView(R.id.main_progress)View progress;
    @InjectView(R.id.share_submit)View shareView;
    @InjectView(R.id.share_content)EditText contentView;
    @InjectView(R.id.layout_main)View main;

    private static final int SUBMIT_SHARE = 0x0002;

    private ChampionCommentAdapter activityAdapter;

    private WalnutCommentServiceHandler serviceHandler;
    private WalnutCommentHandler handler;

    private String providerId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_champion_comment);

        ButterKnife.inject(this);

        progress.setVisibility(View.VISIBLE);

        serviceHandler = new WalnutCommentServiceHandler(this);
        handler = new WalnutCommentHandler(this);

        init();
    }

    private void init() {
        logoImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        swipeRefreshLayout.setColorSchemeResources(R.color.swipe_color_1
                , R.color.swipe_color_2
                , R.color.swipe_color_3
                , R.color.swipe_color_4);

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (!swipeRefreshLayout.isRefreshing()) {
                    swipeRefreshLayout.setRefreshing(true);
                }
                refreshNewReviews();
            }
        });

        commentList.setOnLoadMoreListener(new PullupToMoreListView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                refreshOldReviews();
            }
        });

        shareView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                share();
            }
        });

        main.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WalnutUtils.closeInputMethod(ChampionCommentActivity.this);
            }
        });

        commentList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                WalnutUtils.closeInputMethod(ChampionCommentActivity.this);
            }
        });

        initData();
    }

    private void share() {
        String content = contentView.getText().toString();

        if (content.length() < 1) {
            return;
        }

        int userId = PrefUtils.getUserId(this);
        String name = PrefUtils.getPrefUser(this);

        RestAdapter adapter = RetrofitNetworkService.makeAsyncRestAdapter();
        serviceHandler.share(adapter, userId, name, providerId, content, handler, SUBMIT_SHARE);
        progress.setVisibility(View.VISIBLE);
    }

    private void initData() {
        /*
        List<CommentModel> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            CommentModel model = new CommentModel();
            model.setContent("这是评论，好，非常好。\n好，多行的来试一下");
            model.setUserNick("宇智波鼬");
            model.setTime("2015-08-01 21:30");
            list.add(model);
        }

        activityAdapter = new ChampionCommentAdapter(list, this);
        commentList.setAdapter(activityAdapter);
        */
        providerId = getIntent().getStringExtra("providerId");

        RestAdapter adapter = RetrofitNetworkService.makeAsyncRestAdapter();
        serviceHandler.retrieveReviews(adapter, providerId, handler, WalnutNotifyHandler.INIT_ACHIEVE_DATA);
        progress.setVisibility(View.VISIBLE);
    }

    private void refreshNewReviews() {
        //RestAdapter adapter = RetrofitNetworkService.makeAsyncRestAdapter();
        // serviceHandler.retrieveReviews(adapter, 0, handler, WalnutNotifyHandler.INIT_ACHIEVE_DATA);
        swipeRefreshLayout.setRefreshing(false);
    }

    private void refreshOldReviews() {
        commentList.onLoadMoreComplete();
    }

    private static class WalnutCommentHandler
            extends WalnutBaseNofityHandler<ChampionCommentActivity, CommentModel> {

        public WalnutCommentHandler(ChampionCommentActivity championCommentActivity) {
            super(championCommentActivity);
        }

        @Override
        public void doInitData(ChampionCommentActivity championCommentActivity, List<CommentModel> data) {
            get().activityAdapter = new ChampionCommentAdapter(data, get());
            get().commentList.setAdapter(get().activityAdapter);

            get().swipeRefreshLayout.setRefreshing(false);
            get().progress.setVisibility(View.GONE);
        }

        @Override
        public void handleOtherMessage(Message msg) {
            get().progress.setVisibility(View.GONE);

            switch (msg.what) {
                case SUBMIT_SHARE:
                    Bundle bundle = msg.getData();
                    String ok = (String)bundle.getSerializable(RetrofitNetworkService.RESULT_DATA);
                    if ("ok".equalsIgnoreCase(ok)) {
                        int userId = PrefUtils.getUserId(get());
                        String name = PrefUtils.getPrefUser(get());
                        CommentModel model = new CommentModel();
                        model.setCreateTime(System.currentTimeMillis() / 1000);
                        model.setContent(get().contentView.getText().toString());
                        model.setUserId(userId);
                        model.setUserNick(name);
                        model.setUserIcon(PrefUtils.getPrefUserProfileImg(get()));
                        // model.setProviderId(get().providerId);
                        get().activityAdapter.refreshData(model);
                        get().contentView.setText("");
                        WalnutUtils.closeInputMethod(get());
                    } else {
                        Toast.makeText(get(), "评论失败!", Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    }
}
